<template>
  <div
    class="product-spotlight"
    :class="{ reverse: reverse }"
    @mousemove="handleMouseMove"
    @mouseleave="handleMouseLeave"
  >
    <div
      class="relative min-h-screen flex items-center"
      :class="reverse ? 'flex-row-reverse' : 'flex-row'"
    >
      <!-- 文本区域 -->
      <div ref="textContent" class="w-1/2 p-10" :class="reverse ? 'pl-20' : 'pr-20'">
        <h2 ref="titleElement" class="text-6xl font-bold mb-8 opacity-0 transform translate-y-10">
          {{ title }}
        </h2>

        <div
          v-if="price"
          ref="priceElement"
          class="text-3xl font-bold mb-6 opacity-0 transform translate-y-10"
        >
          {{ formattedPrice }}
        </div>

        <p ref="descElement" class="text-xl mb-10 opacity-0 transform translate-y-10">
          {{ description }}
        </p>

        <!-- 规格信息 -->
        <div
          v-if="specs.length > 0"
          ref="specsElement"
          class="mb-10 opacity-0 transform translate-y-10"
        >
          <h3 class="text-xl font-semibold mb-4">产品特点</h3>
          <ul class="space-y-2">
            <li v-for="(spec, index) in specs" :key="index" class="flex items-center">
              <svg
                class="w-5 h-5 mr-2 text-green-500"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              {{ spec }}
            </li>
          </ul>
        </div>

        <!-- 按钮组 -->
        <div class="flex flex-wrap gap-4">
          <button
            ref="button"
            class="relative overflow-hidden group transform-gpu"
            :style="buttonStyle"
            @click="handleDetailsClick"
          >
            <div
              class="relative z-10 px-8 py-4 text-lg font-medium transition-colors bg-black text-white group-hover:text-black"
            >
              {{ buttonText }}
            </div>
            <div
              class="absolute inset-0 transform origin-left scale-x-0 bg-white transition-transform duration-500 ease-out group-hover:scale-x-100"
            ></div>
          </button>

          <button
            v-if="price"
            ref="buyButton"
            class="relative overflow-hidden group transform-gpu"
            :style="buttonStyle"
            @click="handleBuyClick"
          >
            <div
              class="relative z-10 px-8 py-4 text-lg font-medium transition-colors bg-white text-black border-2 border-black group-hover:text-white"
            >
              立即购买
            </div>
            <div
              class="absolute inset-0 transform origin-left scale-x-0 bg-black transition-transform duration-500 ease-out group-hover:scale-x-100"
            ></div>
          </button>
        </div>
      </div>

      <!-- 图片区域 -->
      <div ref="imageWrapper" class="w-1/2 h-[80vh] relative overflow-hidden">
        <div ref="imageReveal" class="absolute inset-0 bg-black transform translate-x-0 z-10"></div>
        <div ref="imageInner" class="relative w-full h-full transform" :style="imageStyle">
          <template v-if="!imageError">
            <div
              v-if="!imageLoaded"
              class="absolute inset-0 flex items-center justify-center bg-gray-100"
            >
              <div
                class="w-10 h-10 border-4 border-black border-t-transparent rounded-full animate-spin"
              ></div>
            </div>
            <img
              :src="imageUrl"
              :alt="title"
              ref="image"
              class="absolute inset-0 w-full h-full object-cover opacity-0 transform scale-110 transition-transform duration-500"
              :class="{ 'opacity-100 scale-100': imageLoaded }"
              @load="handleImageLoad"
              @error="handleImageError"
              loading="lazy"
            />
          </template>
          <div v-else class="absolute inset-0 flex items-center justify-center bg-gray-100">
            <div class="text-center text-gray-500">
              <svg
                class="w-16 h-16 mx-auto mb-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                />
              </svg>
              <p>图片加载失败</p>
            </div>
          </div>
          <div class="absolute inset-0 bg-gradient-to-b from-transparent to-black/20"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

// 注册插件并确保全局可用
gsap.registerPlugin(ScrollTrigger)
if (typeof window !== 'undefined') {
  window.gsap = gsap
  window.ScrollTrigger = ScrollTrigger
}

const props = defineProps({
  title: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  imageUrl: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    default: null,
  },
  specs: {
    type: Array,
    default: () => [],
  },
  buttonText: {
    type: String,
    default: '了解更多',
  },
  buyLink: {
    type: String,
    default: '#',
  },
  reverse: {
    type: Boolean,
    default: false,
  },
})

// 引用元素
const textContent = ref(null)
const titleElement = ref(null)
const descElement = ref(null)
const priceElement = ref(null)
const specsElement = ref(null)
const button = ref(null)
const buyButton = ref(null)
const imageWrapper = ref(null)
const imageReveal = ref(null)
const imageInner = ref(null)
const image = ref(null)

// 状态管理
const mousePos = ref({ x: 0.5, y: 0.5 })
const isImageLoaded = ref(false)
const imageLoaded = ref(false)
const imageError = ref(false)

// 计算样式
const imageStyle = computed(() => {
  if (!imageLoaded.value) return {}

  const { x, y } = mousePos.value
  const moveX = (x - 0.5) * 20
  const moveY = (y - 0.5) * 20

  return {
    transform: `translate3d(${moveX}px, ${moveY}px, 0) scale(${imageLoaded.value ? '1' : '1.1'})`,
    transition: 'transform 0.3s ease-out, opacity 0.6s ease-out',
    opacity: imageLoaded.value ? '1' : '0',
  }
})

const buttonStyle = computed(() => ({
  opacity: imageLoaded.value ? '1' : '0',
  transform: `translate3d(0, ${imageLoaded.value ? '0' : '20px'}, 0)`,
  transition: 'transform 0.6s ease-out, opacity 0.6s ease-out',
}))

// 鼠标移动处理
const handleMouseMove = (e) => {
  if (!imageLoaded.value) return

  const rect = imageWrapper.value?.getBoundingClientRect()
  if (!rect) return

  mousePos.value = {
    x: (e.clientX - rect.left) / rect.width,
    y: (e.clientY - rect.top) / rect.height,
  }
}

const handleMouseLeave = () => {
  mousePos.value = { x: 0.5, y: 0.5 }
}

// 图片加载处理
const handleImageLoad = () => {
  if (imageError.value) return

  imageLoaded.value = true
  isImageLoaded.value = true

  // 使用 nextTick 确保 DOM 更新后再初始化动画
  nextTick(() => {
    initAnimations()
  })
}

const handleImageError = () => {
  imageError.value = true
  imageLoaded.value = false
  isImageLoaded.value = false
  console.error('图片加载失败:', props.imageUrl)
}

// 图片延迟加载处理
const observer = ref(null)

onMounted(() => {
  if ('IntersectionObserver' in window) {
    observer.value = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            // 预加载图片
            const img = new Image()
            img.onload = handleImageLoad
            img.onerror = handleImageError
            img.src = props.imageUrl
            observer.value.disconnect()
          }
        })
      },
      {
        rootMargin: '50px 0px',
        threshold: 0.1,
      },
    )

    if (imageWrapper.value) {
      observer.value.observe(imageWrapper.value)
    }
  } else {
    // 降级处理：如果不支持 IntersectionObserver，直接加载图片
    handleImageLoad()
  }
})

onBeforeUnmount(() => {
  if (observer.value) {
    observer.value.disconnect()
  }
})

// 初始化动画
const initAnimations = () => {
  // 确保所有需要的元素都存在
  if (
    !textContent.value ||
    !titleElement.value ||
    !descElement.value ||
    !button.value ||
    !imageReveal.value ||
    !image.value
  ) {
    console.warn('Some elements are not ready for animation')
    return
  }

  // 创建主时间轴
  const masterTl = gsap.timeline({
    scrollTrigger: {
      trigger: textContent.value,
      start: 'top center+=20%',
      end: 'bottom center',
      toggleActions: 'play none none reverse',
    },
  })

  // 文本动画序列
  masterTl
    .from(titleElement.value, {
      y: 100,
      opacity: 0,
      duration: 1.2,
      ease: 'power4.out',
    })
    .from(
      priceElement.value,
      {
        y: 30,
        opacity: 0,
        duration: 0.8,
        ease: 'power3.out',
      },
      '-=0.8',
    )
    .from(
      descElement.value,
      {
        y: 50,
        opacity: 0,
        duration: 1,
        ease: 'power3.out',
      },
      '-=0.6',
    )
    .from(
      specsElement.value,
      {
        y: 30,
        opacity: 0,
        duration: 0.8,
        ease: 'power3.out',
      },
      '-=0.8',
    )
    .from(
      [button.value, buyButton.value].filter(Boolean),
      {
        y: 30,
        opacity: 0,
        duration: 0.8,
        stagger: 0.1,
        ease: 'power3.out',
      },
      '-=0.6',
    )

  // 图片揭示动画
  if (imageWrapper.value && imageReveal.value) {
    gsap.to(imageReveal.value, {
      xPercent: props.reverse ? -100 : 100,
      duration: 1.2,
      ease: 'power4.inOut',
      scrollTrigger: {
        trigger: imageWrapper.value,
        start: 'top center+=20%',
        end: 'bottom center',
        toggleActions: 'play none none reverse',
      },
    })
  }

  // 图片动画
  if (image.value) {
    gsap.fromTo(
      image.value,
      {
        scale: 1.1,
        opacity: 0,
      },
      {
        scale: 1,
        opacity: 1,
        duration: 1.5,
        ease: 'power4.out',
        scrollTrigger: {
          trigger: imageWrapper.value,
          start: 'top center+=20%',
          end: 'bottom center',
          toggleActions: 'play none none reverse',
        },
      },
    )
  }
}

// 合并到单个 onMounted 钩子
onMounted(() => {
  // 设置图片预加载
  const preloadImage = new Image()
  preloadImage.src = props.imageUrl

  if (preloadImage.complete) {
    isImageLoaded.value = true
    handleImageLoad()
  } else {
    preloadImage.onload = () => {
      isImageLoaded.value = true
      handleImageLoad()
    }
  }

  // 设置 Intersection Observer
  if ('IntersectionObserver' in window && imageWrapper.value) {
    observer.value = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !isImageLoaded.value) {
            handleImageLoad()
            observer.value?.disconnect()
          }
        })
      },
      {
        rootMargin: '50px 0px',
        threshold: 0.1,
      },
    )

    observer.value.observe(imageWrapper.value)
  }
})

// 使用emit向父组件传递事件
const emit = defineEmits(['openDetails', 'addToCart'])

const handleDetailsClick = () => {
  emit('openDetails')
}

const handleBuyClick = (e) => {
  e.preventDefault()
  emit('addToCart')
}

const formattedPrice = computed(() => {
  if (props.price === null) return ''
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
  }).format(props.price)
})
</script>

<style>
.product-spotlight {
  position: relative;
  overflow: hidden;
}

.product-spotlight::after {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(to bottom, transparent 60%, rgba(0, 0, 0, 0.05));
  pointer-events: none;
}

.button-hover-effect {
  position: relative;
  overflow: hidden;
}

.button-hover-effect::before {
  content: '';
  position: absolute;
  inset: 0;
  background: white;
  transform-origin: left;
  transform: scaleX(0);
  transition: transform 0.3s ease-out;
}

.button-hover-effect:hover::before {
  transform: scaleX(1);
}

/* 添加交互动效 */
.product-spotlight img {
  transition: transform 0.6s cubic-bezier(0.215, 0.61, 0.355, 1);
}

.product-spotlight:hover img {
  transform: scale(1.05);
}

/* 文本渐变效果 */
.text-gradient {
  background: linear-gradient(to right, #000, #333);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 性能优化相关样式 */
.product-spotlight {
  contain: content;
}

.product-spotlight img {
  contain: strict;
  will-change: transform, opacity;
}

/* 骨架屏动画 */
@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

.skeleton-loading {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

/* 优化动画性能 */
.transform-gpu {
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

/* 响应式优化 */
@media (max-width: 1024px) {
  .product-spotlight > div {
    flex-direction: column !important;
  }

  .product-spotlight > div > div {
    width: 100% !important;
    padding: 2rem !important;
  }

  .product-spotlight h2 {
    font-size: 3rem;
  }

  .product-spotlight .imageWrapper {
    height: 60vh !important;
  }
}

@media (max-width: 640px) {
  .product-spotlight h2 {
    font-size: 2rem;
  }

  .product-spotlight .text-xl {
    font-size: 1rem;
  }

  .product-spotlight button {
    width: 100%;
    margin-bottom: 1rem;
  }
}

/* 增强动画效果 */
.product-spotlight button {
  transition: transform 0.3s ease;
}

.product-spotlight button:hover {
  transform: translateY(-2px);
}

.product-spotlight button:active {
  transform: translateY(0);
}
</style>
